package org.feng.common.constant;

import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * 公共枚举接口
 *
 * @author feng
 */
public interface IBaseEnum<CT> {

    CT getCode();

    String getDesc();

    static <Y, S extends IBaseEnum<Y>> S getEnum(Y code, S[] enumClass) {
        return getEnumOrDefault(code, enumClass, null);
    }

    static <Y, S extends IBaseEnum<Y>> S getEnumOrDefault(Y code, S[] enumClass, S defaultVal) {
        return code == null ? defaultVal : getOptionEnum(code, enumClass).orElse(defaultVal);
    }

    static <Y, S extends IBaseEnum<Y>> S getEnumOrThrow(Y code, S[] enumClass, Supplier<Exception> exceptionSupplier) throws Exception {
        if (code == null) {
            throw exceptionSupplier.get();
        }
        return getOptionEnum(code, enumClass).orElseThrow(exceptionSupplier);
    }

     private static <Y, S extends IBaseEnum<Y>> Optional<S> getOptionEnum(Y code, S[] enumClass) {
        return  Arrays.stream(enumClass).filter(entity -> Objects.equals(entity.getCode(), code)).findFirst();
    }
}
